import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState,
} from 'react';

import type { FowardRefYearRange } from '@/pages/InventoryAnalysis/components/search/YearRange';
import YearRange from '@/pages/InventoryAnalysis/components/search/YearRange';
import { DatePicker, DatePickerProps, Tooltip } from 'antd';
import { RangePickerProps } from 'antd/lib/date-picker';
import { SelectBox } from 'devextreme-react';
// import { Button, Modal } from 'antd';
import type { FowardZtSelect } from '@/pages/InventoryAnalysis/components/search/ZtSelect';
import ZtSelect from '@/pages/InventoryAnalysis/components/search/ZtSelect';
import { SettingOutlined } from '@ant-design/icons';
import { useModel } from 'umi';
import './_style.less';
const { RangePicker } = DatePicker;

const dateFormat = 'YYYY';

export interface SearchRenderAProps {
  yearDate: string[] | null; //2024
  Transaction_Type?: string[];
  ChangeTransactionType?: any;
  setSummeryCallback?: any;
  pageType?: any;
  formDisabled?: any;
  ztValue?: string | null;
}

export interface FowardSearchRenderA {
  getFormSearchValues: () => SearchRenderAProps;
}

const SearchRenderC = forwardRef(
  (props: SearchRenderAProps, ref: React.ForwardedRef<FowardSearchRenderA>) => {
    const {
      yearDate: propsYearDate,
      ztValue: propsZtValue,
      Transaction_Type,
      ChangeTransactionType,
      setSummeryCallback,
      pageType,
      formDisabled = false,
    } = props;
    const { initialState } = useModel('@@initialState');
    const { zcbfName } = initialState?.curPart as any;
    const yearDateModel: any = useModel('qjModel');
    const ztSelectRef = useRef<FowardZtSelect | null>(null);
    const ztModel = useModel('ztModel');

    const { ztDates, dataList } = ztModel;
    const ztDataListOptions = useMemo(() => {
      if (dataList && dataList.length > 0) {
        return dataList.map((item: any) => {
          return {
            label: item.displayName,
            value: item.Data_ID,
          };
        });
      }
      return [];
    }, [dataList]);
    const [displaydataId, SetdisplaydataId] = useState<any>(`[${ztDates.at(-1)}]${zcbfName}`);
    useEffect(() => {
      ztModel.refresh();
    }, []);

    useEffect(() => {
      // setDates(ztDates);
    }, [ztDates]);
    const yearRangeRef = useRef<FowardRefYearRange | null>(null);

    const QueryType = useRef({ TransactionType: '全部', SummeryType: '按汇总方式' });
    const CuurentYear = useRef<any[]>([]);
    const defalutZtValue = useMemo(() => {
      if (propsZtValue !== null && propsZtValue !== undefined) {
        return propsZtValue;
      }
      return ztDataListOptions.length > 0
        ? ztDataListOptions[ztDataListOptions.length - 1].value
        : null;
    }, [propsZtValue, ztDataListOptions]);
    const defaultYearDateValue = useMemo(() => {
      if (propsYearDate !== null && propsYearDate !== undefined) {
        return propsYearDate;
      } else if (ztDates) {
        return ztDates;
      } else {
        return [];
      }
    }, [propsYearDate, ztModel]);

    const OnClickSetSummeryCallback = (
      a: any,
      e: any | DatePickerProps['value'] | RangePickerProps['value'],
      c?: any,
    ) => {
      if ('业务类型' === a) {
        QueryType.current.TransactionType = e;
      }
      if ('统计方式' === a) {
        QueryType.current.SummeryType = e;
      } else if (a === '年度单') {
        // SetdisplaydataId(e.itemData.displayName);
        // CuurentYear.current = [e.itemData.Data_ID, e.itemData.Data_ID];
      }
      setSummeryCallback(e, a);
    };
    const startYearDate = defaultYearDateValue?.length === 0 ? '' : defaultYearDateValue[0];
    const endYearDate =
      defaultYearDateValue?.length === 0
        ? ''
        : defaultYearDateValue[defaultYearDateValue.length - 1];

    useImperativeHandle(
      ref,
      () => {
        return {
          getFormSearchValues: () => {
            let selectYearDate: any = yearRangeRef.current?.getYearDateValue() || [''];
            const ztSelectValue = ztSelectRef.current?.getZtValue() || '';
            if (ztSelectValue !== '') {
              selectYearDate = {
                startYear: ztSelectValue,
                endYear: ztSelectValue,
                dates: [ztSelectValue],
              };
            }
            return {
              ...selectYearDate,
              TransactionType: QueryType.current.TransactionType,
              SummeryType: QueryType.current.SummeryType,
            };
          },
        };
      },
      [],
    );

    return (
      <>
        <div
          className={'custom-search-panel '}
          style={{ display: 'flex', marginRight: '0 !important' }}
        >
          <div style={{ display: 'flex', alignItems: 'center' }}>
            {pageType !== '商品仓库出入库统计' && (
              <>
                <YearRange
                  startDate={startYearDate}
                  endDate={endYearDate}
                  ref={yearRangeRef}
                  // onChangeCallBack={OnClickSetSummeryCallback.bind(this, '年度')}
                />
              </>
            )}
            {pageType === '商品仓库出入库统计' && (
              <>
                <div style={{ paddingLeft: 3 }}>
                  <span style={{ marginRight: 3, marginLeft: 2 }}>账套：</span>
                  <ZtSelect
                    ref={ztSelectRef}
                    value={defalutZtValue}
                    option={ztDataListOptions}
                    disabled={formDisabled}
                  />
                </div>
                {/* <SelectBox
                  width="220"
                  className="custom-search-panel_NO"
                  style={{ marginRight: 0 }}
                  // items={[dataList]}
                  dataSource={dataList}
                  value={displaydataId}
                  valueExpr="displayName"
                  displayExpr="displayName"
                  onItemClick={OnClickSetSummeryCallback.bind(this, '年度单')}
                  // defaultValue={ztDates.at(-1)}
                  dropDownOptions={{
                    width: '250px',
                  }}
                ></SelectBox> */}
              </>
            )}
          </div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div style={{ margin: '0 8px' }}>业务类型：</div>
            <SelectBox
              width="120"
              height={'34'}
              //   style={{ margin: '0 8px' }}
              dataSource={Transaction_Type}
              //   value={'全部'}
              className="custom-search-panel_NO"
              onValueChange={OnClickSetSummeryCallback.bind(this, '业务类型')}
              defaultValue={'全部'}
              dropDownOptions={{
                width: '150px',
              }}
            ></SelectBox>
            <Tooltip title={'标准业务类型设置'} placement="bottom">
              <SettingOutlined
                color="#4f2d7f"
                style={{
                  marginRight: 10,
                  marginLeft: 5,
                  display: 'flex',
                  alignItems: 'center',
                  fontSize: 17,
                }}
                onClick={OnClickSetSummeryCallback.bind(this, '业务类型设置')}
              />
            </Tooltip>
            {/* <Button
              text="业务类型设置"
              type="default"
              icon={'w'}
              style={{ margin: '0 10px' }}
              onClick={}
            ></Button> */}
          </div>
          {pageType !== '商品仓库出入库统计' && (
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ width: '70px', margin: '0 8px' }}>统计方式：</div>
              <SelectBox
                width="120"
                height={'34'}
                // style={{ marginRight: '10px !important' }}
                dropDownOptions={{
                  width: '150px',
                }}
                className="custom-search-panel_NO"
                onValueChange={OnClickSetSummeryCallback.bind(this, '统计方式')}
                dataSource={['按汇总方式', '按批次方式']}
                defaultValue={'按汇总方式'}
              ></SelectBox>
            </div>
          )}
        </div>
      </>
    );
  },
);

export default SearchRenderC;
